const { DataTypes } = require('sequelize');
const sequelize = require('../config/db');

const Account = sequelize.define('Account', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'Users',
      key: 'id'
    }
  },
  categoryId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'Categories',
      key: 'id'
    }
  },
  name: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  url: {
    type: DataTypes.STRING(255),
    allowNull: true,
    validate: {
      // 自定义URL验证规则，更灵活地接受URL格式
      isUrl(value) {
        if (value && value.trim()) {
          // 检查是否以http://或https://开头
          if (!value.startsWith('http://') && !value.startsWith('https://')) {
            throw new Error('URL必须以http://或https://开头');
          }
          // 基本格式检查，至少包含一个点
          if (!value.includes('.')) {
            throw new Error('URL格式不正确，请包含域名');
          }
        }
      }
    }
  },
  username: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  password: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  note: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  createdAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updatedAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
});

// 关联关系
Account.associate = function(models) {
  Account.belongsTo(models.User, { foreignKey: 'userId' });
  Account.belongsTo(models.Category, { foreignKey: 'categoryId' });
};

module.exports = Account;